package com.zxb.user.interceptor;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
public class MyLoadBalancerAutoConfiguration {


    @MyLoadBalanced
    @Autowired(required = false) //限定注入到list的RestTemplate
    private List<RestTemplate> restTemplates = Collections.emptyList();

    @Bean
    public MyLoadBalancerInterceptor myLoadBalancerInterceptor(LoadBalancerClient loadBalancerClient){
        return new MyLoadBalancerInterceptor(loadBalancerClient);
    }

    @Bean
    public SmartInitializingSingleton myLoadBalancedRestTemplateInitialize(MyLoadBalancerInterceptor myLoadBalancerInterceptor){
        //Spring 拓展点
        return ()->{
            for (RestTemplate restTemplate : MyLoadBalancerAutoConfiguration.this.restTemplates) {
                List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(restTemplate.getInterceptors());
                //填充拦截器
                interceptors.add(myLoadBalancerInterceptor);
                restTemplate.setInterceptors(interceptors);
            }
        };
    }

}
